<template>
	<a-modal v-bind="options" class="apply-invoice-dialog">
		<div class="invOrgs" v-if="detail.length > 1">
			<exclamation-circle-filled style="color: #faad14ff" />
			该开票申请存在{{ detail.length }}个开票主体，将会生成{{ detail.length }}条开票申请。
		</div>

		<div
			v-if="
				[2].includes(dataDetails.value?.approvalStatus) ||
				(dataDetails.value?.approvalStatus === 3 && dataDetails.value?.invoiceType === 1 && dataDetails.value?.status === 2)
			"
			class="invOrgs">
			<exclamation-circle-filled v-color="{color: COLOR_MAP.warning}" />
			<span v-color="{color: COLOR_MAP.warning}" class="failure-reason">
				{{ dataDetails.value?.approvalStatus === 2 ? '驳回' : '失败' }}原因 :【{{ '失败原因' }}】
			</span>
		</div>

		<a-form ref="formRef" :model="formData" :rules="rules" layout="vertical">
			<!-- 发票详情 -->
			<a-descriptions title="发票详情" :column="4" class="ant-descriptions-blockquote">
				<template v-if="props.pageType === 2">
					<a-descriptions-item span="1">
						<a-form-item label="发票号码：" name="invoiceNo">
							<a-input v-model:value="formData.invoiceNo" placeholder="请输入发票号码" />
						</a-form-item>
					</a-descriptions-item>
					<a-descriptions-item span="3"></a-descriptions-item>
				</template>

				<a-descriptions-item>
					<a-form-item label="发票类型：" name="invoiceKind">
						<a-select
							v-model:value="formData.invoiceKind"
							:disabled="pageType === 3"
							:options="invoiceKindOptions"
							placeholder="请选择发票类型" />
					</a-form-item>
				</a-descriptions-item>

				<a-descriptions-item>
					<a-form-item label="抬头类型：" name="buyerType">
						<a-radio-group v-model:value="formData.buyerType" :disabled="pageType === 3">
							<a-radio :value="2">企业单位</a-radio>
							<a-radio
								:value="1"
								v-if="formData.invoiceKind === 1 || formData.invoiceKind === 3 || formData.invoiceKind === 5">
								个人/非企业
							</a-radio>
						</a-radio-group>
					</a-form-item>
				</a-descriptions-item>

				<a-descriptions-item>
					<a-form-item label="发票抬头：" name="buyerName" v-if="formData.buyerType === 1">
						<a-input v-model:value="formData.buyerName" :maxlength="40" placeholder="请输入发票抬头" :disabled="pageType === 3" />
					</a-form-item>

					<a-form-item label="发票抬头：" name="buyerName" v-if="formData.buyerType === 2">
						<!-- <a-select v-model:value="formData.buyerName" v-bind="searchOption" :disabled="pageType === 3">
							<template v-if="loadings.search" #notFoundContent>
								<a-spin spinning tip="正在搜索，请稍候……" />
							</template>
							<template #dropdownRender="{menuNode: menu}">
								<v-nodes :vnodes="menu" />
								<a-divider style="margin: 4px 0" />
								<a-space style="padding: 4px 8px">
									<a-button type="text" @mousedown.prevent="addItem">
										<template #icon>
											<plus-outlined />
										</template>
										添加当前输入的企业名称
									</a-button>
								</a-space>
							</template>
						</a-select> -->
						<a-auto-complete
						:maxlength="10"		v-model:value="formData.buyerName"
							v-bind="searchOption">
							<template #default="item">
										<a-input
										v-model:value="formData.buyerName"
										:maxlength="40"
										@input="handleInput"
										placeholder="请输入的企业名称" />
							</template>
							<template v-if="loadings.search" #notFoundContent>
								<a-spin spinning tip="正在搜索，请稍候……" />
							</template>
						</a-auto-complete>
					</a-form-item>
				</a-descriptions-item>

				<a-descriptions-item>
					<a-form-item label="税号：" name="buyerTaxpayerNum" v-if="formData.buyerType === 2">
						<a-input v-model:value="formData.buyerTaxpayerNum" placeholder="请输入税号" :disabled="pageType === 3" />
					</a-form-item>
				</a-descriptions-item>

				<a-descriptions-item>
					<a-form-item label="详细地址：" name="buyerAddress" :rules="[{required: formData.invoiceKind === 2}]">
						<a-input
							v-model:value="formData.buyerAddress"
							placeholder="请输入详细地址"
							:maxLength="100"
							:disabled="pageType === 3" />
					</a-form-item>
				</a-descriptions-item>

				<a-descriptions-item>
					<a-form-item label="联系电话：" name="buyerTel">
						<a-input
							v-model:value="formData.buyerTel"
							placeholder="请输入联系电话"
							:maxLength="20"
							:disabled="pageType === 3" />
					</a-form-item>
				</a-descriptions-item>

				<a-descriptions-item>
					<a-form-item label="开户银行：" name="buyerBankName" :rules="[{required: formData.invoiceKind === 2}]">
						<a-input
							v-model:value="formData.buyerBankName"
							placeholder="请输入开户银行"
							:maxLength="100"
							:disabled="pageType === 3" />
					</a-form-item>
				</a-descriptions-item>

				<a-descriptions-item>
					<a-form-item label="银行账号：" name="buyerBankAccount" :rules="[{required: formData.invoiceKind === 2}]">
						<a-input
							v-model:value="formData.buyerBankAccount"
							placeholder="请输入银行账号"
							:maxLength="50"
							:disabled="pageType === 3" />
					</a-form-item>
				</a-descriptions-item>

				<a-descriptions-item span="4">
					<a-form-item label="备注：" name="remark">
						<a-textarea
							v-model:value="formData.remark"
							show-count
							:maxlength="100"
							placeholder="请输入备注信息"
							:disabled="pageType === 3" />
					</a-form-item>
				</a-descriptions-item>
			</a-descriptions>

			<a-typography-text strong>
				<blockquote>缴费详情</blockquote>

				<!-- for循环需要缴费的数组 -->
				<template v-for="(item, index) in detail" :key="index">
					<div class="subject" v-if="props.pageType === 1">开票主体：{{ item.invOrgName }}</div>

					<div class="flex record-main" v-else>
						<div class="title">开票主体：</div>

						<a-select
							v-model:value="item.invOrgId"
							:options="invOrgOptioins"
							:disabled="(props.pageType === 2 && props.resubmitId) || pageType === 3"
							placeholder="请选择开票主体"
							@change="
								e => {
									item.invOrgName = e.label
								}
							"
							style="width: 285px; margin-right: 10px" />

						<a-input
							v-if="item.invOrgId === -1"
							v-model:value="item.invOrgName"
							:disabled="(props.pageType === 2 && props.resubmitId) || pageType === 3"
							placeholder="请输入开票主体"
							:maxLength="50"
							style="width: 285px" />
					</div>

					<vxe-grid ref="grid" v-bind="gridOptions" :data="item.detailItems" :loading="loadings.detail">
						<template #price="{row}">
							<a-input-number
								v-model:value="row.price"
								:class="{error: row.price < 0}"
								:min="0"
								:max="row.invoiceMoney"
								:precision="2"
								:disabled="props.pageType === 1 || (props.pageType === 2 && props.resubmitId) || pageType === 3"
								placeholder="请输入金额"
								style="width: 100%"
								@change="priceChange(item, index)" />
						</template>

						<template #pageTaxRate="{row}">
							<a-input-number
								v-model:value="row.pageTaxRate"
								:min="0"
								:max="999"
								:precision="0"
								placeholder="请输入税率"
								addon-after="%"
								style="width: 100%"
								:disabled="props.pageType === 1 || (props.pageType === 2 && props.resubmitId) || pageType === 3"
								@change="priceChange(item, index)" />
						</template>

						<template #action="{row}">
							<a-button v-if="!props.resubmitId" type="link" @click="deleteDetail(row)" :disabled="pageType === 3">
								删除
							</a-button>
						</template>

						<template #bottom>
							<vxe-toolbar perfect>
								<template #buttons>
									价税合计：
									<span v-color="{color: COLOR_MAP.blue}">{{ item.price?.toFixed(2) }}元</span>
									&nbsp;&nbsp; 税额合计：
									<span v-color="{color: COLOR_MAP.blue}">{{ item.taxPriceTotal?.toFixed(2) }}元</span>
									&nbsp;&nbsp;税后合计：
									<span v-color="{color: COLOR_MAP.blue}">{{ item.afterTaxTotal?.toFixed(2) }}元</span>
								</template>
							</vxe-toolbar>
						</template>
					</vxe-grid>
					<br />
				</template>
			</a-typography-text>

			<!-- 收件人信息 -->
			<a-descriptions title="收件人信息" :column="4" class="ant-descriptions-blockquote">
				<a-descriptions-item>
					<a-form-item label="姓名：" name="takerName">
						<a-input
							v-model:value="formData.takerName"
							placeholder="请输入收件人姓名"
							:maxLength="16"
							:disabled="pageType === 3" />
					</a-form-item>
				</a-descriptions-item>

				<a-descriptions-item>
					<a-form-item label="手机号码：" name="takerTel">
						<a-input
							v-model:value="formData.takerTel"
							placeholder="请输入收件人手机号码"
							:maxLength="11"
							:disabled="pageType === 3" />
					</a-form-item>
				</a-descriptions-item>

				<a-descriptions-item>
					<a-form-item label="邮箱地址：" name="takerEmail" :rules="[{type: 'email', required: props.pageType === 1}]">
						<a-input
							v-model:value="formData.takerEmail"
							placeholder="开票成功后将发送发票至该邮箱"
							:maxLength="50"
							:disabled="pageType === 3" />
					</a-form-item>
				</a-descriptions-item>

				<a-descriptions-item></a-descriptions-item>
			</a-descriptions>
		</a-form>

		<template #footer>
			<a-button type="primary" @click="submit">{{ pageType === 3 ? '处理' : '提交申请' }}</a-button>
		</template>
	</a-modal>

	<a-modal
		class="tips-dialog"
		v-model:visible="visibles.tips"
		centered
		title="开票信息确认"
		destroy-on-close
		@cancel="loadings.submit = false">
		<template #footer>
			<a-button type="primary" :loading="loadings.submit" @click="success()">确认</a-button>
		</template>
		<p class="tips">
			<span>发票类型</span>
			<span>{{ invoiceKindOptions[formData.invoiceKind - 1].label }}</span>
		</p>
		<p class="tips">
			<span>发票抬头</span>
			<span style="width: 80%; white-space: revert; text-align: right">{{ formData.buyerName }}</span>
		</p>
		<p class="tips">
			<span>邮箱地址</span>
			<span>{{ formData.takerEmail }}</span>
		</p>
	</a-modal>
</template>

<script lang="ts" setup>
	import {reactive, ref, toRef, watchEffect, watch, defineComponent} from 'vue'
	import {VxeGridInstance, VxeGridProps} from 'vxe-table'
	import {FormInstance, message} from 'ant-design-vue'
	import {formatDate} from 'yuxin-base/src/utils/date'
	import {invoicingDetails, resubmitInvoicing, historicalBlueEdit, approvalHandle} from '@/api/invoicing-history'
	import invoicing from '@/api/invoicing'
	import {ExclamationCircleFilled, PlusOutlined} from '@ant-design/icons-vue'
	import XEUtils from 'xe-utils'
	import {orientationList, favouredPolicyList} from '@/utils/billing-history-status'
	import {COLOR_MAP} from 'yuxin-base/src/constant'
	import {orgInfoAvailableList} from '@/api/invoice-administration'
	import InvitationSignature from '../tenant/invitation-signature.vue'

	const VNodes = defineComponent({
		props: {
			vnodes: {
				type: Object,
				required: true
			}
		},
		render() {
			return this.vnodes
		}
	})
    const handleInput = () => {
      formData.buyerName = formData.buyerName.replace(/\s/g, '')
    }
	const addItem = e => {
		e.preventDefault()
		const hasOption = searchOption.options.some(e => e.name === searchOption.searchInput)
		if (hasOption) {
			message.warning('当前已有企业名称，无法添加')

			return
		}
		if (searchOption.searchInput.length > 40) {
			message.warning('当前企业名称超过40字，无法添加')

			return
		}
		searchOption.options.unshift({
			name: searchOption.searchInput,
			isShift: true,
			taxpayerNum: new Date().getTime()
		})
	}

	const props = withDefaults(
		defineProps<{
			// 重新提交
			resubmitId?: string
			//租客端申请id
			applyId?: string
			billDetailItems?: Array<any>
			dataSource?: any
			//等于3 来自租客端申请处理
			pageType: any
			deptId?: any
			visible: boolean
		}>(),
		{
			pageType: 1
		}
	)

	const visibles = reactive({
		tips: false
	})

	const loadings = reactive({
		search: false,
		submit: false,
		detail: false
	})

	// 发票抬头搜索
	const searchOption = reactive<any>({
		options: [],
		allowClear: true,
		showSearch: true,
		searchInput: '',
		optionFilterProp: 'name',
		// placeholder: '请输入输入企业名称',
		fieldNames: {label: 'name', value: 'taxpayerNum'},
		style: {
			width: '100%'
		},
		onSearch(like: string) {
			searchOption.searchInput = like

			if (searchOption.searchInput.length > 40) {
				message.warning('当前企业名称超过40字，无法添加')

				return
			}
			if (like.length >= 2 && like.trim()) {
				buyerNameSearch(like)
			}
		},
		onblur(e) {
			e.preventDefault()
			return false
		},
		onSelect(value: string) {
			searchOption.options.forEach(e => {
				if (e.taxpayerNum === value) {
					formData.buyerName = e.name
					if (!e.isShift) formData.buyerTaxpayerNum = e.taxpayerNum
				}
			})
			formRef.value?.clearValidate()
		},
		onDeselect() {
			formData.buyerName = ''
			formData.buyerTaxpayerNum = ''
		},
		getPopupContainer(triggerNode: HTMLDivElement) {
			return triggerNode ? triggerNode.parentNode : document.body
		}
	})

	const buyerNameSearch = XEUtils.debounce((like: string) => {
		let params = {
			name: like
		}

		loadings.search = true
		invoicing
			.matching(params)
			.then((res: any) => {
				searchOption.options = res.data
			})
			.finally(() => (loadings.search = false))
	}, 300)

	const invoiceKindOptions = ref<any>([])

	const invOrgOptioins = ref<any>()

	const detail = ref<any>([])
	const formRef = ref<FormInstance>()

	const formData = reactive<any>({
		invoiceKind: 1,
		buyerType: 2,
		buyerName: null,
		buyerTaxpayerNum: null,
		buyerAddress: null,
		buyerTel: null,
		buyerBankName: null,
		buyerBankAccount: null,
		remark: null,
		takerName: null,
		takerTel: null,
		takerEmail: null,
		invoiceNo: null,
		// 修改
		invOrgItemId: null
	})

	const rules: {
		[key: string | number]: any
	} = {
		invoiceNo: [
			{
				required: true,
				message: '请输入发票号码'
			}
		],
		invoiceKind: [
			{
				required: true,
				message: '请选择发票类型'
			}
		],
		buyerType: [
			{
				required: true,
				message: '请选择抬头类型'
			}
		],
		buyerName: [
			{
				required: true,
				message: '请输入发票抬头'
			}
		],
		buyerTaxpayerNum: [
			{
				required: true,
				message: '请输入税号'
			}
		]
	}

	const emits = defineEmits(['update:visible', 'close', 'success'])
	const options = reactive({
		title: '申请开票',
		width: 1300,
		centered: true,
		maskClosable: false,
		destroyOnClose: true,
		confirmLoading: true,
		visible: toRef(props, 'visible'),
		onCancel() {
			emits('close')
			emits('update:visible', false)
			detail.value.totalMoney = 0
			formRef.value?.resetFields()
		}
	})

	const dataDetails = ref<any>({})
	const billData = ref<any>([])
	const grid = ref<VxeGridInstance>()

	const gridOptions = reactive<VxeGridProps>({
		size: 'small',
		maxHeight: 300,
		showOverflow: true,
		rowConfig: {
			isHover: true
		},
		columns: [
			{
				field: 'period',
				fixed: 'left',
				align: 'center',
				title: '期数',
				minWidth: 100
			},
			{
				field: 'feeSubjectName',
				title: '费用类型',
				minWidth: 200
			},
			{
				field: 'invoiceMoney',
				title: '可开票金额(元)',
				minWidth: 200
			},
			{
				slots: {
					default: 'price'
				},
				title: '本次开票金额(元)',
				minWidth: 200
			},
			{
				slots: {
					default: 'pageTaxRate'
				},
				title: '开票税率',
				minWidth: 200
			},
			{
				field: 'taxPrice',
				title: '开票税额(元)',
				minWidth: 200
			},
			{
				field: 'afterTaxPrice',
				title: '开票税后金额(元)',
				minWidth: 200
			},
			{
				// field: 'preferentialPolicyType',
				title: '优惠政策',
				minWidth: 200,
				formatter({row}) {
					return favouredPolicyList[row.preferentialPolicyType].label
				}
			},
			{
				field: 'hasInvoicingMoney',
				title: '已开票金额(元)',
				minWidth: 200
			},
			{
				title: '费用周期',
				minWidth: 350,
				formatter({row}) {
					return formatDate(row.beginTime) + ' 至 ' + formatDate(row.endTime)
				}
			},
			{
				field: 'predictTime',
				title: '应收日期',
				minWidth: 200
			},
			{
				field: 'originalMoney',
				title: '应收(元)',
				minWidth: 200
			},
			{
				field: 'practicalTime',
				title: '已收时间',
				minWidth: 200
			},
			{
				field: 'occurredMoney',
				title: '已收(元)',
				minWidth: 200
			},
			{
				field: 'notOccurredMoney',
				title: '待收(元)',
				minWidth: 200
			},
			{
				slots: {
					default: 'action'
				},
				fixed: 'right',
				align: 'center',
				title: '操作',
				minWidth: 100
			}
		]
	})

	watch(
		() => props.visible,
		newVal => {
			if (newVal) {
				console.log('resubmitId+pageType====', props?.resubmitId, props?.pageType)
				if (props?.resubmitId || props?.pageType === 3) {
					getInvoiceDetails(props?.resubmitId || props?.applyId)
				}

				let titleArr = ['申请开票', '发票录入']
				options.title = titleArr[props.pageType - 1] || '申请开票'

				invoiceKindOptions.value = [
					{label: '增值税电子普通发票', value: 1},
					{label: '增值税电子专用发票', value: 2},
					{label: '电子发票（普通发票）', value: 3},
					{label: '电子发票（增值税专用发票）', value: 4}
				]

				if (props.pageType === 2) {
					invoiceKindOptions.value.push({label: '增值税普通发票', value: 5}, {label: '增值税专用发票', value: 6})
				}

				if (props.billDetailItems?.length && !props.resubmitId && props?.pageType !== 3) {
					getView()
				}

				console.log('🚀 ~ file: apply-invoice.vue:500 ~ options.title:', options.title, props.pageType)
			}
		}
	)

	watch(
		() => formData.invoiceKind,
		newVal => {
			if (newVal && props?.pageType !== 3) {
				getView()
			}

			if (newVal === 2 || newVal === 4) {
				formData.buyerType = 2
			}

			console.log('formData.invoiceKind-----change', formData.invoiceKind)
		}
	)

	watch(
		() => formData.buyerType,
		newVal => {
			if (newVal) {
				console.log('🚀 ~ file: apply-invoice.vue:457 ~ newVal:', newVal)
				// 个人清除税号
				if (newVal === 1) {
					formData.buyerTaxpayerNum = ''
				}
				if (!props.resubmitId && props.visible && props?.pageType !== 3) {
					getView()
				}
			}
		}
	)

	const priceChange = (item: any, index: any) => {
		item.price = 0
		item.taxPriceTotal = 0
		item.afterTaxTotal = 0

		detail.value[index].detailItems.forEach(j => {
			// 页面上的税率需要除100 因为是整数 后台需要小数
			j.taxRate = j.pageTaxRate / 100

			item.price += j.price
			// 税额=本次开票金额/（1+税率） 税后金额=本次开票金额-税额
			j.afterTaxPrice = (j.price / (1 + j.taxRate)).toFixed(2)
			j.taxPrice = (j.price - j.afterTaxPrice).toFixed(2)
			item.taxPriceTotal += Number(j.taxPrice)
		})
		item.afterTaxTotal += Number(item.price - item.taxPriceTotal)

		if (grid.value) {
			grid.value[index].reloadData(detail.value[index].detailItems)
		}
	}

	const refresh = () => {
		detail.value.map(item => {
			item.price = 0
			item.taxPriceTotal = 0
			item.afterTaxTotal = 0
			item.detailItems.forEach(j => {
				item.price += j.price
				// 税后金额=本次开票金额/（1+税率） 税额=本次开票金额-税后金额
				j.afterTaxPrice = (j.price / (1 + j.taxRate)).toFixed(2)
				j.taxPrice = (j.price - j.afterTaxPrice).toFixed(2)
				item.taxPriceTotal += Number(j.taxPrice)
			})
			item.afterTaxTotal += Number(item.price - item.taxPriceTotal)
		})
	}

	const getView = () => {
		loadings.detail = true
		// enterContractId enterpriseId
		let params: any = {
			billDetailItems: props.billDetailItems,
			contractId: props.dataSource?.id,
			buyerType: formData.buyerType,
			invoiceKind: formData.invoiceKind,
			isAddRecord: [5, 6].includes(formData.invoiceKind) ? 1 : null
		}

		if (props.dataSource?.contractType == 2) {
			params.enterContractId = props.dataSource?.id
		}

		invoicing
			.getview(params)
			.then(({data}) => {
				data.forEach(e => {
					e.detailItems.forEach(j => {
						// 页面展示
						j.pageTaxRate = j.taxRate * 100
					})
				})
				detail.value = data
				refresh()
			})
			.catch(() => {
				detail.value = []
				if (grid.value) {
					grid.value[0].reloadData([])
				}
			})
			.finally(() => {
				loadings.detail = false
			})

		if ([2, 3].includes(props.pageType)) {
			getInvOrg()
		}
	}

	const deleteDetail = (item: any) => {
		detail.value.forEach(e => {
			e.detailItems = e.detailItems.filter(j => j.billDetailId !== item.billDetailId)
		})
		refresh()
	}

	// 提交申请
	const submit = () => {
		formRef.value?.validate().then(() => {
			if (detail.value?.some((e: any) => e.invOrgId === -1 && !e.invOrgName)) {
				message.warning('开票主体不能为空')
				return
			}
			if (!detail.value.filter(e => e.detailItems.length)) {
				message.warning('开票主体项不能为空')
				return
			}

			if (formData.takerTel && formData.takerTel.length != 11) {
				message.warning('手机号码格式不正确')
				return
			}
			// 需要再次确认
			visibles.tips = true
		})
	}

	const success = () => {
		loadings.submit = true

		if (!props.resubmitId) {
			// if(invOrgName)

			let data = props.dataSource
			let params = {
				...formData,
				orgItemFormList: detail.value.filter(e => e.detailItems.length),
				renterName: [1, 4].includes(data?.contractType) ? data.renterInfo.name : data?.enterPriseDTO.linkmanName,
				renterPhone: [1, 4].includes(data?.contractType) ? data.renterInfo.phone : data?.enterPriseDTO.linkmanPhone
			}
			// 租客合同 contractId传id 包租合同详情 enterContractId 包租合同子合同 contractId传id enterContractId传enterPriseContractId
			if (data?.contractType === 1 || data?.contractType === 4) {
				params.contractId = data?.id
			}
			if (data?.contractType === 2) {
				params.enterContractId = data?.id
			}
			if (data?.contractType === 2 && data.enterPriseContractId) {
				params.contractId = data?.id
				params.enterContractId = data.enterPriseContractId
			}
			if (props?.pageType === 3) {
				let params = {
					approvalStatus: 1,
					orgItemId: props.applyId
				}

				approvalHandle(params)
					.then(({data}) => {
						message.success('操作成功')
						formRef.value?.resetFields()
						emits('close')
						emits('update:visible', false)
					})
					.finally(() => {
						visibles.tips = false
						loadings.submit = false
					})
			} else {
				let req = invoicing.blue
				// 发票补录
				if (props.pageType === 2) {
					req = invoicing.historicalBlue

					params.orgItemFormList = params.orgItemFormList.map(e => {
						let temp = {...e}
						if (temp.invOrgId === -1) {
							delete temp.invOrgId
						}
						return temp
					})
				}

				req(params)
					.then(({data}) => {
						message.success('开票申请提交成功')
						formRef.value?.resetFields()
						emits('close')
						emits('update:visible', false)
					})
					.finally(() => {
						visibles.tips = false
						loadings.submit = false
					})
			}
		} else {
			let req = resubmitInvoicing
			let params = {
				...formData,
				houseNo: dataDetails.value?.houseNo,
				houseAddress: dataDetails.value?.houseAddress,
				id: dataDetails.value?.id,
				renterName: dataDetails.value?.renterName,
				renterPhone: dataDetails.value?.renterPhone,
				orgItem: detail.value[0]
			}

			if (props.pageType === 2) {
				req = historicalBlueEdit
				params.invOrgItemId = formData.invOrgItemId
			}

			console.log(dataDetails.value?.houseAddress)
			req(params)
				.then(() => {
					message.success('开票申请提交成功')
					emits('close')
					emits('success')
					emits('update:visible', false)
				})
				.finally(() => {
					visibles.tips = false
					loadings.submit = false
				})
		}
	}

	// 获取开票详情 --回显
	const getInvoiceDetails = id => {
		invoicingDetails(id).then((res: any) => {
			detail.value = []
			dataDetails.value = res.data
			// invoiceDetails.value = res.data
			formData.invoiceKind = res.data?.invoiceKind
			formData.buyerType = res.data?.buyerType
			formData.buyerName = res.data?.buyerName
			formData.buyerTaxpayerNum = res.data?.buyerTaxpayerNum
			formData.buyerAddress = res.data?.buyerAddress
			formData.buyerTel = res.data?.buyerTel
			formData.buyerBankName = res.data?.buyerBankName
			formData.buyerBankAccount = res.data?.buyerBankAccount
			formData.remark = res.data?.remark
			formData.takerName = res.data?.takerName
			formData.takerTel = res.data?.takerTel
			formData.takerEmail = res.data?.takerEmail

			if ([2, 3].includes(props.pageType)) {
				getInvOrg(res.data?.departmentId)

				if (props.pageType === 2) {
					formData.invOrgItemId = res.data?.id
					formData.invoiceNo = res.data?.invoiceNumberItems[0]
				}
			}

			loadings.detail = true

			let params = {
				billDetailIds: res.data?.detailItems.map((e: any) => e.billDetailId),
				deptId: res.data?.departmentId
			}
			invoicing
				.getInvoiceAmount(params)
				.then(({data}) => {
					let afterTaxTotal = 0
					let price = 0
					let taxPriceTotal = 0
					billData.value = res.data?.detailItems.map((e: any) => {
						data.forEach((o: any) => {
							if (o.billDetailId === e.billDetailId) {
								e.invoiceMoney = o.hasInvoicingMoney + o.invoiceMoney
							}
						})
						// 页面回显统一处理
						e.pageTaxRate = e.taxRate * 100

						afterTaxTotal += e.afterTaxPrice
						price += e.price
						taxPriceTotal += e.taxPrice
						return e
					})
					detail.value.push({
						afterTaxTotal: afterTaxTotal,
						detailItems: billData.value,
						invOrgId: res.data?.invOrgId || -1,
						invOrgName: res.data?.invOrgName,
						price: price,
						taxPriceTotal: taxPriceTotal
					})
					console.log(detail.value)
				})
				.finally(() => {
					loadings.detail = false
				})
		})
	}

	/** 获取主体类别 */
	const getInvOrg = (departmentId?: any) => {
		const params = {size: 100, status: 3, departmentId: props.deptId || departmentId}
		orgInfoAvailableList(params).then(res => {
			if (!res.data.length) {
				return message.warning('当前无可用的开票主体，请先配置开票主体')
			}

			invOrgOptioins.value = []
			invOrgOptioins.value = res.data.map(i => {
				return {label: i.name, value: i.id}
			})
			invOrgOptioins.value.push({label: '自定义', value: -1})
		})
	}
</script>

<style lang="less">
	.apply-invoice-dialog {
		.invOrgs {
			width: 100%;
			height: 40px;
			line-height: 40px;
			background: #fffbe6;
			color: @warning-color;
			border-radius: 2px 2px 2px 2px;
			opacity: 1;
			border: 1px solid #ffe58f;
			padding-left: 16px;
			margin-bottom: 20px;
		}

		.ant-modal-body {
			overflow: auto;
			min-height: 600px;
			max-height: 900px;
			height: calc(100vh - 150px);
		}

		.ant-descriptions-item-content {
			padding-right: 20px;
		}

		.ant-form-item {
			width: 100%;
			margin: 0;
		}

		.subject {
			width: 100%;
			height: 48px;
			background: #e1edff;
			border-radius: 0px 0px 0px 0px;
			// opacity: 0.12;
			font-size: 14px;
			font-weight: 500;
			color: @primary-color;
			line-height: 48px;
			text-align: center;
		}

		.ant-descriptions-item-content {
			width: 100%;
		}
	}

	.tips-dialog {
		.tips {
			display: flex;
			justify-content: space-between;
		}
	}

	.record-main {
		justify-content: flex-start;
		margin-bottom: 10px;

		.title::before {
			display: inline-block;
			margin-right: 4px;
			color: #ff4d4f;
			font-size: 14px;
			font-family: SimSun, sans-serif;
			line-height: 1;
			content: '*';
		}
	}
</style>
